package com.thread;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class MyBlocking {

	private static  List<Object> list = new ArrayList<>();

	private static Lock lock = new ReentrantLock();

	private static Condition producer = lock.newCondition();
	private static Condition consumer = lock.newCondition();

	public static void main(String[] args) {
		ExecutorService newFixedThreadPool = Executors.newFixedThreadPool(10);
		for (int i = 0; i < 1; i++) {
			Producer producer = new Producer();
			newFixedThreadPool.execute(producer);
		}
		for (int i = 0; i < 10; i++) {
			Consumer consumer = new Consumer();
			newFixedThreadPool.execute(consumer);
		}

	}

	static class Producer implements Runnable {
		public void run() {
			while (true) {
				try {
					lock.lock();
					if (list.size() >= 1) {
						try {
							// 释放锁，当前线程挂起
							producer.await();
							this.wait();
						} catch (InterruptedException e) {
							e.printStackTrace();
						}
					}

					// 生产数据
					list.add("1");
					Thread.sleep(1000);
					System.out.println(Thread.currentThread().getName() + "生产了一个产品，当前队列的长度=" + list.size());
					// 通知其他线程争抢cpu资源`
					consumer.signal();
				} catch (Exception e) {
					e.printStackTrace();
				} finally {
					// 解除锁
					lock.unlock();
				}
  
			}
		}

	}

	static class Consumer implements Runnable {
		public void run() {
			while (true) {
				try {
					lock.lock();
					int size = list.size();
					if (size == 0) {
						System.out.println("消费者线程挂起..." + Thread.currentThread().getName());
						consumer.await();
						System.out
								.println("消费者线程复活..." + Thread.currentThread().getName() + ",list.size=" + list.size());
					}

					int size1 = list.size();
					list.remove(size1 - 1);
					System.out
							.println("消费者线程" + Thread.currentThread().getName() + "正常消费一个...,list.size=" + list.size());
					producer.signal();
				} catch (Exception e) {
					e.printStackTrace();
				} finally {
					lock.unlock();
				}
			}
		}
	}

	private static int getListSize(){
		return list.size();
	}
}
